package com.unittec.drainage.provider.auth.controller;

import java.util.ArrayList;
import java.util.List;

import javax.validation.ValidationException;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.unittec.drainage.provider.auth.entity.SysServiceRouter;
import com.unittec.drainage.provider.auth.service.SysServiceRouterServer;
import com.unittec.drainage.provider.log.Log;
import com.unittec.drainage.provider.utils.ValidationUtils;
import com.unittec.drainage.sdk.auth.request.Req10000;
import com.unittec.drainage.sdk.auth.request.Req101004;
import com.unittec.drainage.sdk.auth.response.Res10000;
import com.unittec.drainage.sdk.log.enums.LogOperateEnum;
import com.unittec.drainage.sdk.log.enums.LogStatusEnum;
import com.unittec.drainage.sdk.root.domain.GatewayRequest;
import com.unittec.drainage.sdk.root.domain.Result;
import com.unittec.drainage.sdk.root.enums.BizCode;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @description 动态路由管理
 * @author Jason
 * @date 2019/11/07
 */
@RestController
@Api(tags = "动态路由管理")
public class SysServiceRouterController {

    @Autowired
    SysServiceRouterServer serviceRouterServer;

    @Autowired
    Log log;

    @RequestMapping(value = "/10000", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "获取系统所有路由信息", notes = "获取系统所有路由信息")
    public Result<List<Res10000>> getAllServiceRouter(@RequestBody GatewayRequest<Req10000> req) {
        try {
            List<SysServiceRouter> list = serviceRouterServer.list();
            List<Res10000> rets = new ArrayList<>();
            Res10000 res = null;
            for (SysServiceRouter sr : list) {
                res = new Res10000();
                BeanUtils.copyProperties(sr, res);
                rets.add(res);
            }
            return Result.success(req, rets);
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            return Result.error(req, e.getMessage());
        }
    }

    @RequestMapping(value = "/10001", method = RequestMethod.POST)
    @ApiOperation(value = "增加路由信息", notes = "增加路由信息")
    @ResponseBody
    public Result<Res10000> saveServiceRouter(@RequestBody GatewayRequest<Req10000> req) {
        log.debug(req, "saveServiceRouter {}  ", "begin");
        long startLogTime = System.currentTimeMillis();
        boolean ok = true;
        try {
            ValidationUtils.validateEntityStr(req.getContent());
            SysServiceRouter sysServiceRouter = new SysServiceRouter();
            BeanUtils.copyProperties(req.getContent(), sysServiceRouter);
            ok = serviceRouterServer.save(sysServiceRouter);
        } catch (Exception e) {
            ok = false;
            log.error(req, e.toString(), e);
            log.addOperateLog("10001", JSON.toJSONString(req), "增加路由信息", log.buildErrmsg(e),
                LogOperateEnum.LOG_ADD.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "saveServiceRouter {}  ", "begin");
        if (ok) {
            log.addOperateLog("10001", JSON.toJSONString(req), "增加路由信息", BizCode.SUCCESS.getMessage(),
                LogOperateEnum.LOG_ADD.getCode(), LogStatusEnum.SUCCESS.getCode(), startLogTime);
            return Result.success(req);
        } else {
            log.addOperateLog("10001", JSON.toJSONString(req), "增加路由信息", BizCode.ERROR.getMessage(),
                LogOperateEnum.LOG_ADD.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, BizCode.ERROR);
        }
    }

    @RequestMapping(value = "/10002", method = RequestMethod.POST)
    @ApiOperation(value = "修改路由信息", notes = "修改路由信息")
    @ResponseBody
    public Result<Res10000> updateServiceRouter(@RequestBody GatewayRequest<Req10000> req) {
        log.debug(req, "updateServiceRouter {}  ", "begin");
        long startLogTime = System.currentTimeMillis();
        QueryWrapper<SysServiceRouter> queryWrapper = new QueryWrapper<>();
        boolean ok = true;
        try {
            ValidationUtils.validateEntityStr(req.getContent());
            SysServiceRouter sysServiceRouter = new SysServiceRouter();
            BeanUtils.copyProperties(req.getContent(), sysServiceRouter);
            ok = serviceRouterServer.update(sysServiceRouter,
                queryWrapper.eq("function_code", req.getContent().getFunctionCode()));
        } catch (Exception e) {
            ok = false;
            log.error(req, e.toString(), e);
            log.addOperateLog("10002", JSON.toJSONString(req), "修改路由信息", log.buildErrmsg(e),
                LogOperateEnum.LOG_UPDATE.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "updateServiceRouter {} ", "end");
        if (ok) {
            log.addOperateLog("10002", JSON.toJSONString(req), "修改路由信息", BizCode.SUCCESS.getMessage(),
                LogOperateEnum.LOG_UPDATE.getCode(), LogStatusEnum.SUCCESS.getCode(), startLogTime);
            return Result.success(req);
        } else {
            log.addOperateLog("10002", JSON.toJSONString(req), "修改路由信息", BizCode.ERROR.getMessage(),
                LogOperateEnum.LOG_UPDATE.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, BizCode.ERROR);
        }
    }

    @RequestMapping(value = "/10003", method = RequestMethod.POST)
    @ApiOperation(value = "删除路由信息", notes = "删除路由信息")
    @ResponseBody
    public Result<Res10000> deleteServiceRouter(@RequestBody GatewayRequest<Req10000> req) {
        log.debug(req, "deleteServiceRouter {}  ", "begin");
        long startLogTime = System.currentTimeMillis();
        QueryWrapper<SysServiceRouter> queryWrapper = new QueryWrapper<>();
        boolean ok = true;
        try {
            if (StringUtils.isBlank(req.getContent().getFunctionCode())) {
                throw new ValidationException("接口编码为空");
            }
            ok = serviceRouterServer.remove(queryWrapper.eq("function_code", req.getContent().getFunctionCode()));
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            log.addOperateLog("10003", JSON.toJSONString(req), "删除路由信息", log.buildErrmsg(e),
                LogOperateEnum.LOG_DEL.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "deleteServiceRouter {}  ", "begin");
        if (ok) {
            log.addOperateLog("10003", JSON.toJSONString(req), "删除路由信息", BizCode.SUCCESS.getMessage(),
                LogOperateEnum.LOG_DEL.getCode(), LogStatusEnum.SUCCESS.getCode(), startLogTime);
            return Result.success(req);
        } else {
            log.addOperateLog("10003", JSON.toJSONString(req), "删除路由信息", BizCode.ERROR.getMessage(),
                LogOperateEnum.LOG_DEL.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, BizCode.ERROR);
        }
    }

    @RequestMapping(value = "/10004", method = RequestMethod.POST)
    @ApiOperation(value = "获取单个路由信息", notes = "获取单个路由信息")
    @ResponseBody
    public Result<Res10000> getServiceRouter(@RequestBody GatewayRequest<Req101004> req) {
        try {
            if (StringUtils.isBlank(req.getContent().getFunctionCode())) {
                throw new ValidationException("接口编码为空");
            }
            LambdaQueryWrapper<SysServiceRouter> queryWrapper = new LambdaQueryWrapper<>();
            SysServiceRouter sysServiceRouter = serviceRouterServer
                .getOne(queryWrapper.eq(SysServiceRouter::getFunctionCode, req.getContent().getFunctionCode()));
            Res10000 res10000 = new Res10000();
            if (sysServiceRouter != null) {
                BeanUtils.copyProperties(sysServiceRouter, res10000);
            }
            log.debug(req, "getServiceRouter {}  ", "end");
            return Result.success(req, res10000);
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            return Result.error(req, e.getMessage());
        }
    }
}
